package com.wlhse.service.impl;

import com.github.pagehelper.PageHelper;
import com.wlhse.dao.*;
import com.wlhse.dto.PoiProblemDto;
import com.wlhse.dto.ProblemMessageDto;
import com.wlhse.dto.inDto.ProblemImportInDto;
import com.wlhse.dto.outDto.ProblemImportDto;
import com.wlhse.entity.Mail;
import com.wlhse.entity.ProblemDescriptionPojo;
import com.wlhse.exception.WLHSException;
import com.wlhse.service.ProblemImportService;
import com.wlhse.util.HashUtil;
import com.wlhse.util.R;
import com.wlhse.util.SendMessageUtil;
import com.wlhse.util.UseCountUtil;
import com.wlhse.util.state_code.CodeDict;
import com.wlhse.util.state_code.NR;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


@Service
public class ProblemImportServiceImpl implements ProblemImportService {

    @Resource
    private ProblemImportDao problemImportDao;

    @Resource
    private ProblemDao problemDao;

    @Resource
    private SendMessageUtil sendMessageUtil;

    @Resource
    private PoiProblemDao poiProblemDao;

    @Resource
    private UseCountUtil useCountUtil;

    @Value("${RESOURCES_URL}")
    private String url;

    @Resource
    private ProblemDescriptionPojo problemDescriptionPojo;

    @Resource
    private CheckItemDao checkItemDao;

    @Resource
    private LeaderCheckItemDao leaderCheckItemDao;

    private static final int checkItemStep = 4;


    @Override
    //领导审核完成下达消息 待完成
    @Transactional
    public String updateProblemImport(ProblemImportDto problemImportDto, Integer userId) {
        if (StringUtils.isNotBlank(problemImportDto.getProblemRank())) {
            String[] str = problemDescriptionPojo.getScorePenalty(problemImportDto.getProblemRank());
            problemImportDto.setLostScore(Double.parseDouble(str[0]));
            problemImportDto.setPenalty(Integer.parseInt(str[1]));
        }
        if (problemImportDao.updateProblemImportDto(problemImportDto) <= 0)
            throw new WLHSException("更新失败");
        updateProblemImportMessage(problemImportDto, userId);
        return NR.r();
    }

    private void updateProblemImportMessage(ProblemImportDto problemImportDto, Integer userId) {
        ProblemMessageDto dto = poiProblemDao.getProblemMessageDto(problemImportDto.getProblemID());
        String orderNumber = StringUtils.isNotBlank(dto.getOrderNumber()) ? dto.getOrderNumber() : "计划外";
        String message = "任务单号:" + orderNumber + " 检查项:" +
                dto.getCheckItemName1() + "_" + dto.getCheckItemName2() + "_" + dto.getCheckItemName3();
        //发给checkPerson
        if (StringUtils.isNotBlank(problemImportDto.getStatus())) {
            if (problemImportDto.getStatus().equals("审核未通过") && dto.getCheckPersonId() != null) {
                Mail mail = sendMessageUtil.getMail(CodeDict.SEND_PROBLEM_NO_PASS, userId, dto.getCheckPersonId(), message);
                sendMessageUtil.sendMessage(mail);
            }
            if (problemImportDto.getStatus().equals("未审核") && dto.getCheckPersonId() != null && dto.getPublishID() != null) {
                Mail mail = sendMessageUtil.getMail(CodeDict.SEND_PROBLEM_EXAMINE, dto.getCheckPersonId(), dto.getPublishID(), message);
                sendMessageUtil.sendMessage(mail);
            }
            //发给公司所有人
            if (problemImportDto.getStatus().equals("未整改")) {
                //生产管理员 RoleCode:2000
                List<Integer> allEmployee = poiProblemDao.getEmpIdByComRole(dto.getCompanyCode(), "2000");
                allEmployee.add(dto.getCheckPersonId());
                for (Integer integer : allEmployee) {
                    Mail mail = sendMessageUtil.getMail(CodeDict.SEND_PROBLEM_FOUND, userId, integer, message);
                    sendMessageUtil.sendMessage(mail);
                }
            }
        }
    }

    //更新整改内容
    @Override
    @Transactional
    public String updateRectProblemImport(ProblemImportDto problemImportDto, int userId) {
        //设置使用频率缓存
        String redisName = "user_" + userId + "_employee_problem_rectification";
        useCountUtil.useCountSetCache(redisName, problemImportDto.getRectiPersonId());

        if (problemImportDao.updateRectProblemImportDto(problemImportDto) <= 0)
            throw new WLHSException("更新失败");
        sendRectProblemImportMessage(problemImportDto);
        return NR.r();
    }

    private void sendRectProblemImportMessage(ProblemImportDto problemImportDto) {
        ProblemMessageDto dto = poiProblemDao.getProblemMessageDto(problemImportDto.getProblemID());
        String orderNumber = StringUtils.isNotBlank(dto.getOrderNumber()) ? dto.getOrderNumber() : "计划外";
        String message = "任务单号:" + orderNumber + " 检查项:" +
                dto.getCheckItemName1() + "_" + dto.getCheckItemName2() + "_" + dto.getCheckItemName3();
        if (StringUtils.isNotBlank(problemImportDto.getStatus()) && problemImportDto.getStatus().equals("未验证") && dto.getCheckPersonId() != null) {
            Mail mail = sendMessageUtil.getMail(CodeDict.SEND_PROBLEM_RECTI, problemImportDto.getRectiPersonId(), dto.getCheckPersonId(), message);
            sendMessageUtil.sendMessage(mail);
        }
    }

    //更新验证内容
    @Override
    @Transactional
    public String updateVerifyProblemImport(ProblemImportDto problemImportDto, int userId) {
        //设置使用缓存
        String redisName = "user_" + userId + "_employee_problem_verification";
        useCountUtil.useCountSetCache(redisName, problemImportDto.getVerifyPersonEmpID());
        if (problemImportDao.updateVerifyProblemImportDto(problemImportDto) <= 0)
            throw new WLHSException("更新失败");

        //发消息
        sendVerifyProblemImportMessage(problemImportDto);
        return NR.r();
    }

    private void sendVerifyProblemImportMessage(ProblemImportDto problemImportDto) {
        ProblemMessageDto dto = poiProblemDao.getProblemMessageDto(problemImportDto.getProblemID());
        String orderNumber = StringUtils.isNotBlank(dto.getOrderNumber()) ? dto.getOrderNumber() : "计划外";
        String message = "任务单号:" + orderNumber + " 检查项:" +
                dto.getCheckItemName1() + "_" + dto.getCheckItemName2() + "_" + dto.getCheckItemName3();
        if (problemImportDto.getStatus().equals("已验证")) {
            //告知整改人验证通过
            Mail mail = sendMessageUtil.getMail(CodeDict.SEND_PROBLEM_VERIFY, problemImportDto.getVerifyPersonEmpID(), problemImportDto.getRectiPersonId(), message);
            sendMessageUtil.sendMessage(mail);
            if (dto.getPublishID() != null && problemImportDto.getVerifyPersonEmpID() != null && dto.getPublishID() != null) {
                //告知领导问题已解决
                Mail mail1 = sendMessageUtil.getMail(CodeDict.SEND_PROBLEM_VERIFY, problemImportDto.getVerifyPersonEmpID(), dto.getPublishID(), message);
                sendMessageUtil.sendMessage(mail1);
            }
        }
        //告知整改人验证未通过
        if (problemImportDto.getStatus().equals("验证未通过") && problemImportDto.getVerifyPersonEmpID() != null && problemImportDto.getRectiPersonId() != null) {
            Mail mail = sendMessageUtil.getMail(CodeDict.SEND_VERIFY_NO_PASS, problemImportDto.getVerifyPersonEmpID(), problemImportDto.getRectiPersonId(), message);
            sendMessageUtil.sendMessage(mail);
        }
    }

    @Override
    @Transactional
    public void insertProblemImport(ProblemImportDto problemImportDto) {
        //开始缓存计数
        problemImportDao.addProblem(problemImportDto);
    }

    @Override
    public String queryProblemImport(ProblemImportInDto problemImportInDto) {
        //查询所有
        System.out.println("===problem==");
        System.out.println(problemImportInDto.getCheckDate1());
        problemImportInDto.setUrl(url);
        setDate(problemImportInDto);
        System.out.println(problemImportInDto.getCheckDate2());
        if (problemImportInDto.getType().equals("all"))
            return NR.r(problemImportDao.getProblemImportDtoByContiton(problemImportInDto));
        //分页查询
        int total = problemImportDao.getProblemImportDtoCount(problemImportInDto);
        PageHelper.startPage(problemImportInDto.getPageIdx(), problemImportInDto.getPageSize());
        List<ProblemImportDto> list = problemImportDao.getProblemImportDtoByContiton(problemImportInDto);
        return NR.r(list, total, problemImportInDto.getPageIdx());
    }

    private void setDate(ProblemImportInDto problemImportInDto) {
        if (StringUtils.isNotBlank(problemImportInDto.getVerifyDate1()) && StringUtils.isBlank(problemImportInDto.getVerifyDate2())) {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
            problemImportInDto.setVerifyDate2(df.format(new Date()));// new Date()为获取当前系统时间
        }
        if (StringUtils.isNotBlank(problemImportInDto.getCheckDate1()) && StringUtils.isBlank(problemImportInDto.getCheckDate2())) {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
            problemImportInDto.setCheckDate2(df.format(new Date()));// new Date()为获取当前系统时间
        }
    }

    @Override
    public String queryProblemImportById(int id, Integer checkPersonID) {
        return NR.r(problemImportDao.getProblemImportDtoById(id, url, checkPersonID));
    }

    @Override
    @Transactional
    public R newInsertProblemImport(ProblemImportDto problemImportDto, int userId) {
        init(problemImportDto);
        //录入使用人员
        String redisName = "user_" + userId + "_employee_problem_write_check_person";
        useCountUtil.useCountSetCache(redisName, problemImportDto.getCheckPersonID());

        String redisName1 = "user_" + userId + "_employee_problem_write_response_person";
        useCountUtil.useCountSetCache(redisName1, problemImportDto.getResponsePersonID());

        if (problemImportDto.getPlanID() == null || problemImportDto.getPlanID() == -1) {
            problemImportDto.setPlanID(-1);
            problemImportDto.setTaskID(-1);
            problemImportDto.setTaskName("计划外");
        }
        problemImportDto.setPlanContentID(-1);

        String hash = HashUtil.hash(problemImportDto.getCompanyName() + problemImportDto.getCheckDate() + problemImportDto.getDescription() + problemImportDto.getCheckItemCode());
        if (problemImportDao.getHashCount(hash) != 0)
            throw new WLHSException("重复录入问题,请检查!");
        problemImportDto.setHash(hash);
        //立即整改
        if (StringUtils.isNotBlank(problemImportDto.getIsRectOntime()) && problemImportDto.getIsRectOntime().equals("是")) {
            problemImportDao.addProblemIsRectOntime(problemImportDto);
        } else {
            //发送消息
            if (problemImportDto.getPlanID() != -1) newInsertProblemImportMessage(problemImportDto);
            problemImportDto.setRectiPersonId(userId);
            problemImportDao.addNewProblem(problemImportDto);
        }
        return R.ok();
    }

    private void init(ProblemImportDto problemImportDto) {
        String code = problemImportDto.getCheckItemCode();
        if (code.toCharArray()[0] == 'A') {
            problemImportDto.setCheckItemName1(leaderCheckItemDao.getName(code.substring(0, checkItemStep)));
            problemImportDto.setCheckItemName2(leaderCheckItemDao.getName(code));
            problemImportDto.setStatus("未整改");
        } else {
            problemImportDto.setCheckItemName1(checkItemDao.queryByCheckItemCode(code.substring(0, checkItemStep)).getCheckItemName());
            problemImportDto.setCheckItemName2(checkItemDao.queryByCheckItemCode(code.substring(0, checkItemStep * 2)).getCheckItemName());
            problemImportDto.setCheckItemName3(checkItemDao.queryByCheckItemCode(code).getCheckItemName());
            problemImportDto.setStatus("未审核");
        }
    }

    private void newInsertProblemImportMessage(ProblemImportDto problemImportDto) {
        PoiProblemDto dto = poiProblemDao.getOrderNumCheckItem(problemImportDto.getPlanID(), problemImportDto.getCheckItemCode());
        String orderNumber = StringUtils.isNotBlank(dto.getOrderNumber()) ? dto.getOrderNumber() : "计划外";
        String message = "任务单号:" + orderNumber + " 检查项:" +
                dto.getCheckItemName1() + "_" + dto.getCheckItemName2() + "_" + dto.getCheckItemName3();
        Mail mail = sendMessageUtil.getMail(CodeDict.SEND_PROBLEM_EXAMINE, problemImportDto.getCheckPersonID(), dto.getPublishID(), message);
        sendMessageUtil.sendMessage(mail);
    }

    @Override
    @Transactional
    public String deleteProblem(int id) {
        if (problemDao.deleteProblem(id) <= 0)
            throw new WLHSException("删除失败");
        return NR.r();
    }

    @Override
    public String getModificationById(int id) {
        return NR.r(problemImportDao.getModificationById(id));
    }

    @Override
    @Transactional
    public String updateProblemImportDto(ProblemImportDto problemImportDto) {
        if (problemImportDao.updateProblemImportDto(problemImportDto) <= 0)
            throw new WLHSException("更新失败");
        return NR.r();
    }

    @Override
    public String getUpdateProblemById(int problemID) {
        return NR.r(problemImportDao.getUpdateProblemById(problemID, url));
    }

    @Override
    public String selectSomeProblem(ProblemImportInDto problemImportInDto) {
        problemImportInDto.setUrl(url);
        setDate(problemImportInDto);
        if (problemImportInDto.getType().equals("all"))
            return NR.r(problemImportDao.getProblemImportDtoByContitonStatus4(problemImportInDto));
        int total = problemImportDao.getTotalProblemStatus4(problemImportInDto);
        PageHelper.startPage(problemImportInDto.getPageIdx(), problemImportInDto.getPageSize());
        List<ProblemImportDto> list = problemImportDao.getProblemImportDtoByContitonStatus4(problemImportInDto);
        return NR.r(list, total, problemImportInDto.getPageIdx());
    }

    @Override
    public String getProblemImportDtoByStatus2(ProblemImportInDto problemImportInDto) {
        if (problemImportInDto.getType().equals("all"))
            return NR.r(problemImportDao.getProblemImportDtoByStatus2(problemImportInDto));
        int total = problemImportDao.getTotalProblemImportDtoByStatus2(problemImportInDto);
        PageHelper.startPage(problemImportInDto.getPageIdx(), problemImportInDto.getPageSize());
        List<ProblemImportDto> list = problemImportDao.getProblemImportDtoByStatus2(problemImportInDto);
        return NR.r(list, total, problemImportInDto.getPageIdx());
    }
}
